<template>
  <div class="tag-selector">
    <el-select
      v-model="selectedTagIds"
      multiple
      filterable
      remote
      :remote-method="handleSearch"
      :loading="loading"
      placeholder="搜索并选择标签"
      no-data-text="无匹配标签"
      no-match-text="无匹配标签"
      style="width: 100%"
      @change="handleSelectionChange"
    >
      <el-option
        v-for="tag in searchResults"
        :key="tag.id"
        :label="tag.name"
        :value="tag.id"
      >
        <div class="tag-option">
          <el-tag :color="tag.color" size="small" effect="plain">
            {{ tag.name }}
          </el-tag>
          <span class="tag-count">{{ formatUseCount(tag.useCount || 0) }}</span>
        </div>
      </el-option>
    </el-select>

    <!-- 热门标签快速选择 -->
    <div v-if="showHotTags && hotTags.length > 0" class="hot-tags">
      <div class="hot-tags-title">热门标签：</div>
      <div class="hot-tags-list">
        <el-tag
          v-for="tag in hotTags"
          :key="tag.id"
          :color="tag.color"
          :effect="isSelected(tag.id) ? 'dark' : 'plain'"
          class="hot-tag"
          @click="toggleTag(tag)"
        >
          {{ tag.name }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import {
  searchTagsApi,
  getHotTagsApi,
  type SimpleTagInfo,
  formatUseCount
} from "@/api/article-tag";

interface Props {
  /** 已选中的标签ID */
  modelValue?: number[];
  /** 是否显示热门标签 */
  showHotTags?: boolean;
  /** 热门标签数量限制 */
  hotTagsLimit?: number;
}

interface Emits {
  (e: "update:modelValue", value: number[]): void;
  (e: "change", tagIds: number[], tags: SimpleTagInfo[]): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  showHotTags: true,
  hotTagsLimit: 10
});

const emit = defineEmits<Emits>();

// 响应式数据
const loading = ref(false);
const selectedTagIds = ref<number[]>([]);
const searchResults = ref<SimpleTagInfo[]>([]);
const hotTags = ref<SimpleTagInfo[]>([]);
const allSelectedTags = ref<SimpleTagInfo[]>([]);

// 计算属性
const isSelected = (tagId: number) => {
  return selectedTagIds.value.includes(tagId);
};

// 方法
const handleSearch = async (keyword: string) => {
  if (!keyword) {
    searchResults.value = [];
    return;
  }

  try {
    loading.value = true;
    const res = await searchTagsApi(keyword, 20);
    if (res?.code === 200 && Array.isArray(res.data)) {
      searchResults.value = res.data;
    } else {
      searchResults.value = [];
    }
  } catch (error) {
    console.error("搜索标签失败:", error);
    searchResults.value = [];
  } finally {
    loading.value = false;
  }
};

const handleSelectionChange = (tagIds: number[]) => {
  selectedTagIds.value = tagIds;

  // 更新已选标签信息
  allSelectedTags.value = allSelectedTags.value.filter(tag =>
    tagIds.includes(tag.id)
  );

  // 添加新选中的标签信息
  const newTagIds = tagIds.filter(
    id => !allSelectedTags.value.some(tag => tag.id === id)
  );

  newTagIds.forEach(id => {
    const tag =
      searchResults.value.find(t => t.id === id) ||
      hotTags.value.find(t => t.id === id);
    if (tag) {
      allSelectedTags.value.push(tag);
    }
  });

  emit("update:modelValue", tagIds);
  emit("change", tagIds, allSelectedTags.value);
};

const toggleTag = (tag: SimpleTagInfo) => {
  const index = selectedTagIds.value.indexOf(tag.id);
  if (index > -1) {
    selectedTagIds.value.splice(index, 1);
  } else {
    selectedTagIds.value.push(tag.id);
    // 确保标签信息被添加到已选列表
    if (!allSelectedTags.value.some(t => t.id === tag.id)) {
      allSelectedTags.value.push(tag);
    }
  }
  handleSelectionChange(selectedTagIds.value);
};

const loadHotTags = async () => {
  if (!props.showHotTags) return;

  try {
    const res = await getHotTagsApi(props.hotTagsLimit);
    if (res?.code === 200 && Array.isArray(res.data)) {
      hotTags.value = res.data;
    } else {
      hotTags.value = [];
    }
  } catch (error) {
    console.error("加载热门标签失败:", error);
    hotTags.value = [];
  }
};

// 监听外部值变化
watch(
  () => props.modelValue,
  newValue => {
    selectedTagIds.value = [...(newValue || [])];
  },
  { immediate: true }
);

// 生命周期
onMounted(() => {
  loadHotTags();
});
</script>

<style lang="scss" scoped>
.tag-selector {
  .tag-option {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    .tag-count {
      margin-left: 8px;
      font-size: 12px;
      color: #909399;
    }
  }

  .hot-tags {
    margin-top: 12px;

    .hot-tags-title {
      margin-bottom: 8px;
      font-size: 12px;
      color: #606266;
    }

    .hot-tags-list {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;

      .hot-tag {
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
          transform: translateY(-1px);
        }
      }
    }
  }
}
</style>
